package com.linck.im.parse.encode;

import com.google.protobuf.MessageLite;
import com.linck.im.model.proto.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

/**
 * 将相关消息打包Package并确定type
 *
 * @author: linck
 * @create: 2021-01-26
 */
public class PackageEncode extends MessageToMessageEncoder<MessageLite> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessageLite messageLite, List<Object> out) throws Exception {
        out.add(parse(messageLite));
    }

    private static ProtoMsg.Package parse(MessageLite messageLite) {
        if (messageLite instanceof ProtoMsg.LoginInfo) {
            return ProtoMsg.Package.newBuilder()
                    .setMsgType(ProtoMsg.MsgType.LOGIN_INFO)
                    .setLoginInfo((ProtoMsg.LoginInfo) messageLite)
                    .build();
        } else if (messageLite instanceof ProtoMsg.Message) {
            return ProtoMsg.Package.newBuilder()
                    .setMsgType(ProtoMsg.MsgType.MESSAGE)
                    .setMessage((ProtoMsg.Message) messageLite)
                    .build();
        } else if (messageLite instanceof ProtoMsg.SysMsg) {
            return ProtoMsg.Package.newBuilder()
                    .setMsgType(ProtoMsg.MsgType.SYS_MSG)
                    .setSysMsg((ProtoMsg.SysMsg) messageLite)
                    .build();
        } else if (messageLite instanceof ProtoMsg.Friends) {
            return ProtoMsg.Package.newBuilder()
                    .setMsgType(ProtoMsg.MsgType.FRIENDS)
                    .setFriends((ProtoMsg.Friends) messageLite)
                    .build();
        } else if (messageLite instanceof ProtoMsg.HeartBeat) {
            return ProtoMsg.Package.newBuilder()
                    .setMsgType(ProtoMsg.MsgType.HEART_BEAT)
                    .setHeartBeat((ProtoMsg.HeartBeat) messageLite)
                    .build();
        }
        return null;
    }

}
